﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Common;
using WebSite.Core;

namespace WebSite.Admin
{
    public partial class MakeTeam : WebSite.Core.BasePage
    {
        public override bool NeedLogin
        {
            get
            {
                return false;
            }
        }
        protected void Page_Load( object sender, EventArgs e )
        {
            int babyaid ,babybid;
            if (!int.TryParse( Request["babyaid"], out babyaid ) || !int.TryParse( Request["babybid"], out babybid ))
            {
                AlertMessageBack( "宝宝ID必须都为数字" );
                return;
            }

            Maticsoft.BLL.CarrefourCover.Baby babybll = new Maticsoft.BLL.CarrefourCover.Baby();
            
            // 检测宝宝
            var srcbabymodel = babybll.GetModel( babyaid );
            if (srcbabymodel == null || NullableHelper.CastValueType( srcbabymodel.ConfirmTeamId ) != 0)
            {
                AlertMessageBack( "第一个宝宝不存在或已经组队" );
            }
            var destbabymodel = babybll.GetModel( babybid );
            if (destbabymodel == null || NullableHelper.CastValueType( destbabymodel.ConfirmTeamId ) != 0)
            {
                AlertMessageBack( "第二个宝宝不存在或已经组队" );
            }

            // 生成组队图片
            string teamImage = TeamHelper.CombinTeamHead( srcbabymodel.BabyHeadImg, destbabymodel.BabyHeadImg );

            // 组队
            Maticsoft.BLL.CarrefourCover.Team teambll = new Maticsoft.BLL.CarrefourCover.Team();

            var newteamid = teambll.Add( new Maticsoft.Model.CarrefourCover.Team()
            {
                BabyAId = srcbabymodel.Id,
                BabyAName = srcbabymodel.BabyName,
                BabyBId = destbabymodel.Id,
                BabyBName = destbabymodel.BabyName,
                Status = 1,
                TeamHeadImg = teamImage,
                TeamName = srcbabymodel.BabyTeamName,
                TeamVoteNum = 0,
                CreateTime = DateTime.Now,
                Ip = Context.Request.UserHostAddress
            } );

            // 更新baby的冗余信息
            srcbabymodel.ConfirmTeamId = destbabymodel.ConfirmTeamId = newteamid;
            srcbabymodel.ConfirmTeamName = destbabymodel.ConfirmTeamName = srcbabymodel.BabyTeamName;
            babybll.Update( srcbabymodel );
            babybll.Update( destbabymodel );

            AlertMessageBack( "组队成功" );
        }
    }
}